$(function(){
	connection();
});
var websocket;
var concurrentRoom;
var roomlist = new Array(); 

function connection(){
	//websocket = new WebSocket("ws://localhost:8081/filesharingsystem/websocket");
	//websocket = new WebSocket("ws://192.168.0.2:8081/filesharingsystem/websocket");
	websocket = new SockJS(getRootPath_web()+"/websocket");
    /*打开时*/
    websocket.onopen = function(evnt) {
        console.log("  websocket.onopen  ");
    };
    /*处理消息时*/
    websocket.onmessage = function(evnt) {
		
		var msg = JSON.parse(evnt.data);
		switch(msg.pid){
			case '1':
				var text = $('#displayBox').textbox('getText');
				text += msg.source+' ';
				text += msg.timeStamp + '\n';
				text += msg.msgContent + '\n';
				$('#displayBox').textbox('setText',text);
				var scrollTop = $("textarea")[0].scrollHeight;
				$("#_easyui_textbox_input3").scrollTop(scrollTop);
				
				
				break;
			case '0':
				var li='<li>'+msg.msgContent+'<div class="m-right">'+'<a href="javascript:joinRoom(\''+msg.msgContent+'\')"  class="easyui-linkbutton l-btn l-btn-small" group id >join</a>'+'</div>'+'</li>';
				roomlist.push(li);
				$("#group").append(roomlist);
				roomlist.length = 0;
				break;
			case '2':
				$.messager.alert('错误', msg.msgContent,'error');
				break;
		}
        console.log("  websocket.onmessage   ");
	};


    websocket.onerror = function(evnt) {
        console.log("  websocket.onerror  ");
    };

    websocket.onclose = function(evnt) {
        console.log("  websocket.onclose  ");
    };
}

function joinRoom(room){
	if(room!=null && room != ""){
		var msg = {
			pid: "0",
			msgContent: room
		};
		concurrentRoom = room;
		$("#title").text("Chat:"+room);
		/* 发送消息 */
		websocket.send(JSON.stringify(msg));
		$("#inputBox").textbox({editable:true});
		$('#dgbt').click();
	}
}
function createRoom(text){	
	if(text!=null && text != ""){
		var msg = {
			pid: "0",
			msgContent: text
		};
		concurrentRoom = text;
		$("#title").text("Chat:"+text);
		/* 发送消息 */
		websocket.send(JSON.stringify(msg));
		$("#inputBox").textbox({editable:true});
		$("#inputBox").textbox('clear');
		$('#dgbt').click();
	}
}

function getRootPath_web() {
						//获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
	var curWwwPath = window.document.location.href;
						            //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
	var pathName = window.document.location.pathname;
	var pos = curWwwPath.indexOf(pathName);
						            //获取主机地址，如： http://localhost:8083
	var localhostPaht = curWwwPath.substring(0, pos);
	var projectName = pathName.substring(0, pathName.substr(1).indexOf('/')+2);
	return (localhostPaht + projectName);
}